//
//  CZSendComposeViewController.swift
//  GZWeibo007
//
//  Created by danli on 15/12/27.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZSendComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareUI()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //呼出键盘
        textView.becomeFirstResponder()
    }
    
    private func prepareUI()
    {
        prepareNavBar()
        
        view.addSubview(textView)
        textView.ff_Fill(view)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        preparePhotoVC()
        prepareToolBar()
        prepareTipLengthLabel()
    }
    
    private func prepareNavBar()
    {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        prepareTitleView()
    }
    
    private func prepareTitleView()
    {
        let prefix = "发微博"
        
        //获取用户名
        CZUserAccount.loadUserAccount()?.screen_name = nil
        if let userName = CZUserAccount.loadUserAccount()?.screen_name
        {
            //有用户名
            let titleStr = prefix + "\n" + userName
            
            //获取用户名的位置
            let range = (titleStr as NSString).rangeOfString(userName)
            let attributeStr = NSMutableAttributedString(string: titleStr)
            //添加指定字符串的特性
            attributeStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(13), range: range)
            attributeStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            
            titleLabel.attributedText = attributeStr
            
        }else
        {
            //没有用户名
            titleLabel.text = prefix
        }
        navigationItem.titleView = titleLabel
        titleLabel.sizeToFit()
    }
    
    
    var photoVCViewTopConstraint :NSLayoutConstraint?
    func preparePhotoVC()
    {
        
        // 控制器需要添加到子控制中
        self.addChildViewController(photoVC)
        
        let photoVCView = photoVC.view
        view.addSubview(photoVCView)
        photoVCView.backgroundColor = UIColor.greenColor()
        
        photoVCView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[photoVCView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["photoVCView" : photoVCView]))
        photoVCViewTopConstraint = NSLayoutConstraint(item: photoVCView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
        view.addConstraint(photoVCViewTopConstraint!)
        view.addConstraint(NSLayoutConstraint(item: photoVCView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 2.0 / 3, constant: 0))
        // TODO: 添加photoVCView的约束
//        view.addConstraint(ns)
        
        
    }
    
    var toolBarBottomConstraint:NSLayoutConstraint?
    private func prepareToolBar()
    {
        view.addSubview(toolBar)
        let con = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSizeMake(UIScreen.mainScreen().bounds.width, 44))
        toolBarBottomConstraint = toolBar.ff_Constraint(con, attribute: NSLayoutAttribute.Bottom)!
        
        
        //给toolBar添加5个按钮
        // 每个item对应的图片名称, 数组里面有5个字典 imageName 对应的value就是要显示的图片
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_addbutton_background", "action": "add"]]
        
        // 准备一个数组存放工具条的item
        var items = [UIBarButtonItem]()
        for dic in itemSettings
        {
            // 创建工具条btnItem
            let btn = UIBarButtonItem(imageName: dic["imageName"]!)
            items.append(btn)
            // 为btnItem添加事件
            (btn.customView as! UIButton).addTarget(self, action: Selector(dic["action"]!), forControlEvents: UIControlEvents.TouchUpInside)
            
            // 添加弹簧，以完成工具条的布局
            let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(flexibleSpace)
        }
        items.removeLast()
        toolBar.items = items
    }
    
    private func prepareTipLengthLabel()
    {
        view.addSubview(tipLengthLabel)
        
        tipLengthLabel.text = String(textMaxLength)
//        view.sizeToFit()
        tipLengthLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraint(NSLayoutConstraint(item: tipLengthLabel, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -4))
        view.addConstraint(NSLayoutConstraint(item: tipLengthLabel, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: -4))
    }
    
    func keyboardFrameWillChange(notification:NSNotification)
    {
        // 获取键盘的信息
        let userInfo = notification.userInfo!
        // 获取键盘弹出动画时间
        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        
        // 获取键盘动画结束后的Frame值
        let endingFrame = userInfo[UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        toolBarBottomConstraint?.constant = -(UIScreen.mainScreen().bounds.height - endingFrame.origin.y)
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: 工具栏按钮的点击事件
    /// 图片
    func picture()
    {
        photoVCViewTopConstraint?.constant = -view.frame.height * 2.0 / 3
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    /// @某人
    func mention()
    {
        print("mention")
    }
    
    /// #
    func trend()
    {
        print("trend")
    }
    
    /// 表情键盘
    func emoticon()
    {
        // 当textView.inputView == nil的时候，默认调出系统键盘
        // 手动将键盘移除
        textView.resignFirstResponder()
        
        // 移除和呼出键盘的时间相隔太短，系统会直接不做动画，进行键盘切换，所以要延迟0.25秒让键盘移除
        
        self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil
        // USEC_PER_SEC :表示毫秒
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.textView.becomeFirstResponder()
        }
     }
    
    /// 添加
    func add()
    {
        print("add")
    }
    
    func close()
    {
//        SVProgressHUD.dismiss()
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 发送微博
    func sendStatus()
    {
        let text = textView.emoticonText()
        if text.characters.count > textMaxLength
        {
            SVProgressHUD.showErrorWithStatus("文字内容超出范围")
            return
        }
        SVProgressHUD.showWithStatus("正在发送微博")
        CZNetworkTool.sharedInstance.sendStatus(text) { (result, error) -> () in
            if error != nil
            {
                SVProgressHUD.showErrorWithStatus("您的网络不太给力")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
            self.close()
        }
    }
    
    deinit
    {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    let textMaxLength = 25
    
    // MARK: -懒加载
    lazy var titleLabel:UILabel = {
       let label = UILabel()
        label.textAlignment = NSTextAlignment.Center
        label.textColor = UIColor.blackColor()
        label.numberOfLines = 0
        return label
    }()
    
    lazy var textView:CZTextView = {
       let textView = CZTextView()
        textView.font = UIFont.systemFontOfSize(18)
        textView.backgroundColor = UIColor.lightGrayColor()
        textView.textColor = UIColor.blackColor()
        textView.delegate = self
        textView.placeholderText = "分享新鲜事"
        
        // 设置textView垂直方向有弹簧效果
        textView.alwaysBounceVertical = true
        
        // 当拖动时退出键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return textView
    }()
    
    lazy  var toolBar: UIToolbar = UIToolbar()
    
    lazy var emoticonVC:DLEmoticonViewController = DLEmoticonViewController(textView: self.textView)
    
    lazy var tipLengthLabel:UILabel = {
    
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(13)
        label.textColor = UIColor.whiteColor()
//        label.backgroundColor = UIColor.redColor()
        return label
    }()
    
    /// 照片选择器控制器
    lazy var photoVC:DLPhotoSelectorController = DLPhotoSelectorController()
    
}

extension CZSendComposeViewController:UITextViewDelegate
{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
//        SVProgressHUD.showErrorWithStatus("微博内容不能超过140个字符")
        
            let text = textView.emoticonText()
            let length = textMaxLength - text.characters.count
            tipLengthLabel.text = String(length)
            tipLengthLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.whiteColor()
    }
}
